package com.itheima.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program: itcast-MyRPC
 * @description: 链接, 消息管理
 * @author: zhanghz001
 * @create: 2021-02-20 11:08
 **/
@ServerEndpoint("/ws/{userId}")
@Component
public class WebSocketServer {
    //日志
    static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    //在现数量
    private static final AtomicInteger ONLINE_COUNT = new AtomicInteger(0);
    //处理客户端连接socket
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap =
            new ConcurrentHashMap<>();
    
    //会话信息
    private Session session;
    //用户信息
    private String userId = "";
    
    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) {
        //处理session和用户信息
        this.userId = userId;
        this.session = session;
        //
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
        } else {
            webSocketMap.put(userId, this);
            //增加在线人数
            addOnlineCount();
        }
        try {
            //处理连接成功消息的发送
            sendMessage("Server>>>>远程webSocket连接成功");
            log.info("用户" + userId + "成功连接,当前的在线人数为:" + getOnlineCount());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            
        }
    }
    
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            subOnlineCount();
        }
        log.info("用户退出...");
    }
    
    public static synchronized void subOnlineCount() {
        WebSocketServer.ONLINE_COUNT.decrementAndGet();
    }
    
    /**
     * 消息中转
     *
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        if (StringUtils.isNotEmpty(message)) {
            try {
                //解析消息
                JSONObject jsonObject = JSON.parseObject(message);
                String toUserId = jsonObject.getString("toUserId");
                String msg = jsonObject.getString("msg");
                if (StringUtils.isNotEmpty(toUserId) && webSocketMap.containsKey(toUserId)) {
                    webSocketMap.get(toUserId).sendMessage(msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                
            }
        }
    }
    //
    //
    //
    
    /**
     * @param s 服务端想客户端发送数据
     * @throws Exception
     */
    private void sendMessage(String s) throws Exception {
        this.session.getBasicRemote().sendText(s);
    }
    
    /**
     * 增加在线人数
     */
    public static synchronized void addOnlineCount() {
        WebSocketServer.ONLINE_COUNT.incrementAndGet();
    }
    
    /**
     * @return
     */
    public static synchronized AtomicInteger getOnlineCount() {
        return ONLINE_COUNT;
    }
    
    /**
     * @param message 服务器消息推送
     * @param userId
     * @return
     */
    public static boolean sendInfo(String message,
                                   @PathParam("userId") String userId) throws Exception {
        boolean flag = true;
        if (StringUtils.isNotEmpty(userId) && webSocketMap.containsKey(userId)) {
            webSocketMap.get(userId).sendMessage(message);
        } else {
            log.error("用户" + userId + "不在线");
            flag = false;
        }
        return flag;
    }
}
